package sg.edu.nus.iss.stockex;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;

public class CodeDateKey implements WritableComparable<CodeDateKey> {

	private String code = "";
	private long timestamp = 0;

	public void set(String code, long timestamp) {

		this.code = code;
		this.timestamp = timestamp;

	}

	public String getCode() {
		return code;
	}



	public void setCode(String code) {
		this.code = code;
	}



	public long getTimestamp() {
		return timestamp;
	}



	public void setTimestamp(long timestamp) {
		this.timestamp = timestamp;
	}



	@Override
	public void readFields(DataInput in) throws IOException {

		this.code = Text.readString(in);
		this.timestamp = in.readLong();

	}

	@Override
	public void write(DataOutput out) throws IOException {

		Text.writeString(out, code);
		out.writeLong(this.timestamp);
	}

	@Override
	public int compareTo(CodeDateKey other) {
		//System.out.println("$$$ " + this.timestamp + " compare " + other.timestamp);
		
		if (this.code.compareTo(other.code) != 0) {
			return this.code.compareTo(other.code);
		} else if (this.timestamp != other.timestamp) {
			return timestamp < other.timestamp ? -1 : 1;
		} else {
			return 0;
		}

	}

	public static class CodeDateKeyComparator extends WritableComparator {
		public CodeDateKeyComparator() {
			super(CodeDateKey.class);
		}

		public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
			return compareBytes(b1, s1, l1, b2, s2, l2);
		}
	}

	static {
		WritableComparator.define(CodeDateKey.class,
				new CodeDateKeyComparator());
	}

}
